

package com.hazelcast.internal.partition.operation;

import com.hazelcast.internal.partition.IPartitionService;
import com.hazelcast.internal.partition.MigrationCycleOperation;
import com.hazelcast.internal.partition.impl.InternalPartitionServiceImpl;
import com.hazelcast.internal.partition.impl.PartitionDataSerializerHook;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.impl.Versioned;

import java.io.IOException;

/**
 * Sent from the master to check the partition table state stamp on target member.
 *
 * @since 3.12
 */
public final class PartitionStateCheckOperation extends AbstractPartitionOperation implements MigrationCycleOperation, Versioned {

    private long stamp;

    private transient boolean stale;

    public PartitionStateCheckOperation() {
    }

    public PartitionStateCheckOperation(long stamp) {
        this.stamp = stamp;
    }

    @Override
    public void run() {
        ILogger logger = getLogger();
        InternalPartitionServiceImpl partitionService = getService();

        long currentStamp = partitionService.getPartitionStateStamp();
        if (currentStamp != stamp) {
            stale = true;
            if (logger.isFineEnabled()) {
                logger.fine("Partition table is stale! Current stamp: %s, master stamp: %s", currentStamp, stamp);
            }
        }
    }

    @Override
    public Object getResponse() {
        return !stale;
    }

    @Override
    public String getServiceName() {
        return IPartitionService.SERVICE_NAME;
    }

    @Override
    protected void readInternal(ObjectDataInput in) throws IOException {
        super.readInternal(in);
        stamp = in.readLong();
    }

    @Override
    protected void writeInternal(ObjectDataOutput out) throws IOException {
        super.writeInternal(out);
        out.writeLong(stamp);
    }

    @Override
    public int getClassId() {
        return PartitionDataSerializerHook.PARTITION_STATE_CHECK_OP;
    }
}
